package bancosys.tec.persist.spring;

import java.util.List;

import javax.sql.DataSource;

import org.hibernate.cfg.Configuration;
import org.hibernate.event.PostLoadEventListener;

/**
 * @author Cesar Olmos
 */
public class LocalSessionFactoryBean extends org.springframework.orm.hibernate3.LocalSessionFactoryBean {
    private String[] mappingResources;

    private DataSource dataSource;

    private List<PostLoadEventListener> postLoadEventListeners;

    /**
     * {@inheritDoc}
     * 
     * @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setMappingResources(java.lang.String[])
     */
    @Override
    public void setMappingResources(String[] mappingResources) {
        this.mappingResources = mappingResources;
        super.setMappingResources(mappingResources);
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.springframework.orm.hibernate3.AbstractSessionFactoryBean#setDataSource(javax.sql.DataSource)
     */
    @Override
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        super.setDataSource(dataSource);
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.springframework.orm.hibernate3.AbstractSessionFactoryBean#getDataSource()
     */
    @Override
    public DataSource getDataSource() {
        return this.dataSource;
    }

    /**
     * @return {@link String} os mapping resources
     */
    public String[] getMappingResources() {
        String[] result = new String[mappingResources.length];
        System.arraycopy(mappingResources, 0, result, 0, mappingResources.length);
        return result;
    }

    /**
     * Define o postLoadEventListeners.
     * 
     * @param postLoadEventListeners O postLoadEventListeners a ser definido.
     */
    public void setPostLoadEventListeners(List<PostLoadEventListener> postLoadEventListeners) {
        this.postLoadEventListeners = postLoadEventListeners;
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#newConfiguration()
     */
    @Override
    protected Configuration newConfiguration() {
        Configuration config = super.newConfiguration();
        if (this.postLoadEventListeners == null || this.postLoadEventListeners.size() == 0) {
            return config;
        }
        PostLoadEventListener[] oldListeners = config.getEventListeners().getPostLoadEventListeners();
        PostLoadEventListener[] newListeners = new PostLoadEventListener[oldListeners.length + this.postLoadEventListeners.size()];
        System.arraycopy(oldListeners, 0, newListeners, 0, oldListeners.length);
        int i = oldListeners.length;
        for (PostLoadEventListener listener : this.postLoadEventListeners) {
            newListeners[i] = listener;
            i++;
        }
        config.getEventListeners().setPostLoadEventListeners(newListeners);
        return config;
    }
}
